package com.github.common.extend.demo.config.transaction;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.util.Objects;

/**
 * 事务提交回调监听
 * @author X1993
 * @date 2022/6/8
 * @description
 */
@Component
public class TransactionSubmitEventListener implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 注册事务提交回调任务
     * @param runnable
     */
    public void register(Runnable runnable)
    {
        if (TransactionSynchronizationManager.isSynchronizationActive()){
            //开启了事务
            /**
             * 注册事务提交事件 {@link #transactionSubmitCallback(TransactionSubmitCallbackEvent)}
             */
            applicationEventPublisher.publishEvent(new TransactionSubmitCallbackEvent(runnable));
        }else {
            //没有开启事务,立即执行
            runnable.run();
        }
    }

    /**
     * 监听事务提交,执行回调
     * @param callbackEvent
     */
    @TransactionalEventListener
    public void transactionSubmitCallback(TransactionSubmitCallbackEvent callbackEvent){
        callbackEvent.getRunnable().run();
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    private class TransactionSubmitCallbackEvent {

        private final Runnable runnable;

        public TransactionSubmitCallbackEvent(Runnable runnable) {
            Objects.requireNonNull(runnable);
            this.runnable = runnable;
        }

        public Runnable getRunnable() {
            return runnable;
        }

    }

}
